package com.power.sample

import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.power.lib.NavigationBottomBar
import com.power.sample.databinding.ActivityMainBinding
import com.power.sample.frag.FragCommunity
import com.power.sample.frag.FragHome
import com.power.sample.frag.FragMessage
import com.power.sample.frag.FragPersonal

class MainActivity : AppCompatActivity() {

    private val binding: ActivityMainBinding? by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding?.root)
        binding?.lifecycleOwner = this
        initPageModule()
        initBottomTab()
    }

    //主页的四个模块页面
    private fun initPageModule() {
        val pageFragList = mutableListOf<Fragment>()
        pageFragList.add(FragHome())
        pageFragList.add(FragCommunity())
        pageFragList.add(FragMessage())
        pageFragList.add(FragPersonal())

        val pageAdapter = Pager2Adapter(this)
        pageAdapter.setData(pageFragList)
        //默认不做预加载Fragment
        binding?.mainVP2?.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
        binding?.mainVP2?.adapter = pageAdapter

    }

    private fun initBottomTab() {
        val icons = arrayOf(
            BitmapFactory.decodeResource(resources, R.drawable.icon_home_selected),
            BitmapFactory.decodeResource(resources, R.drawable.icon_community_selected),
            BitmapFactory.decodeResource(resources, R.drawable.icon_message_selected),
            BitmapFactory.decodeResource(resources, R.drawable.icon_personal_selected)
        )
        val icons2 = arrayOf(
            BitmapFactory.decodeResource(resources, R.drawable.icon_home_grey),
            BitmapFactory.decodeResource(resources, R.drawable.icon_community_grey),
            BitmapFactory.decodeResource(resources, R.drawable.icon_message_grey),
            BitmapFactory.decodeResource(resources, R.drawable.icon_personal_grey)
        )
        val tabTexts = arrayOf("首页", "社区", "消息", "个人")
        binding?.mainBottomBar?.let {
            it.setSelectedIcons(icons.toList())//选中状态的icon
                .setUnselectIcons(icons2.toList())//未选中状态的icon
                .setTabText(tabTexts.toList())//tab文字
                .setupViewpager(binding?.mainVP2)//配合viewpager2
                .start()//start方法要在最后再调用！
        }
        //注册tab的点击回调事件
        binding?.mainBottomBar?.registerTabClickListener(object :
            NavigationBottomBar.OnBottomTabClickListener {
            override fun tabClick(position: Int) {
                Log.d("tabClick", "position=$position")
            }
        })
    }
}